package com.cpit.platform.security;


import com.cpit.platform.config.GlobalConfig;
import com.cpit.platform.security.handler.LogoutSuccessLogHandler;
import com.cpit.platform.security.handler.RestAuthenticationFailureHandler;
import com.cpit.platform.security.handler.RestAuthenticationSuccessHandler;
import com.cpit.platform.security.service.CustomUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RestAuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private RestAuthenticationSuccessHandler successHandler;
    @Autowired
    private LogoutSuccessLogHandler logoutSuccessLogHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests().antMatchers("/**/app/**").permitAll()
                .antMatchers("/**/getCurrentUser").permitAll()
                .anyRequest().authenticated().and()
                .headers().frameOptions().disable().and()
                .formLogin()
                .failureHandler(authenticationFailureHandler) // failure handler
                .successHandler(successHandler) // success handler
                .loginPage("/" + GlobalConfig.WORK_PROJECT_NAME + "/login").permitAll().and()
                .logout().logoutSuccessHandler(logoutSuccessLogHandler);
    }

    @Bean
    public UserDetailsService customUserService() {
        return new CustomUserService();
    }

    @Autowired
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/assets/**", "/css/**",
                "/images/**", "/js/**", "/jquery/**", "/**/app/**", "/**/download/**");
    }

}
